package com.lzy.cloud.payment.controller;

import com.lzy.cloud.payment.constants.JobDistributePrefix;
import com.lzy.cloud.payment.dtos.pay.RefundMoneyDTO;
import com.lzy.cloud.payment.dtos.payment.MsgOrderRefundDto;
import com.lzy.cloud.payment.facade.PayFacade;
import com.lzy.cloud.payment.facade.PayRefundInfoFacade;
import com.lzy.cloud.payment.remote.BaseApi;
import com.lzy.cloud.payment.response.MemberToken;
import com.lzy.framework.core.cache.cluster.RedisClusterService;
import com.lzy.framework.core.output.Result;
import com.lzy.framework.core.utils.DozerUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RestController
@Slf4j
@RequestMapping("pay/refund")
public class PayRefundInfoController {

    Logger logger = Logger.getLogger(PayRefundInfoController.class);

    @Autowired
    RedisClusterService redisClusterService;

    @Autowired
    PayRefundInfoFacade payRefundInfoFacade;

    @Autowired
    BaseApi baseApi;

    @Autowired
    PayFacade payFacade;

    // 执行时间 0 */5 * * * ?
    // 支付退款更新状态：每5分钟执行一次
    @RequestMapping(value = "/update/status", method = RequestMethod.POST)
    public void updateStatus() {
        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"));
        try {
            Thread.sleep(Long.valueOf(RandomStringUtils.random(3, false, true)));
            // 获取分布式锁
//            kvClient.setNx(JobDistributePrefix.JOB_PAY_REFUND_UPDATE + now, "");
            redisClusterService.setnx(JobDistributePrefix.JOB_PAY_REFUND_UPDATE + now, "");
        } catch (InterruptedException e) {
            logger.error("定时任务：改变支付退款状态======获取分布式锁失败！");
        }
        logger.info("定时任务：改变支付退款状态======开始======：日期：{}");
        //退款中
        payFacade.updateRefundQueryTask();
        logger.info("定时任务：改变支付退款状态======完成======：日期：{}");
    }

    /**
     * 退订退款
     * @param msgOrderRefundDto
     * @return
     */
    @RequestMapping(value = "/unsubscribe",method = RequestMethod.POST)
    public Result unsubscribe(@RequestBody MsgOrderRefundDto msgOrderRefundDto){
        //在线支付退款
        payRefundInfoFacade.onlineRefund(msgOrderRefundDto);
        //余额支付退款
        payRefundInfoFacade.balanceRefund(msgOrderRefundDto);
        return new Result();
    }

}
